package com.test.sdk.provider.controller;

import com.test.sdk.provider.exception.SdkException;
import com.test.sdk.provider.service.UserService;
import com.test.sdk.provider.util.AccountUtil;
import com.test.sdk.provider.util.ErrorConstants;
import com.test.sdk.provider.util.ResponseTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    //?&account=13717967901
    @RequestMapping("user/reg/sendcode.html")
    public ResponseTO sendCode(String account) throws SdkException {
        if (!AccountUtil.checkMobile(account)) {
            throw new SdkException(ErrorConstants.MOBILE_ERROR);
        }
        //验证手机号有没有被注册过
        boolean result = userService.doSendCode(account);
        return new ResponseTO(true, result);
    }

    //?&account=138123123123&password=xxxxxx&repassword=xxxxxx&type=1&code=123
    @RequestMapping("user/register.html")
    public ResponseTO regist(String account, String password, String repassword, Integer type, String code) throws SdkException {
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password) || StringUtils.isEmpty(repassword) || type == null || StringUtils.isEmpty(code)) {
            throw new SdkException(ErrorConstants.PARAM_ERROR);
        }
        if (!password.equals(repassword)) {
            throw new SdkException(ErrorConstants.PASSWORD_NOT_EQUAL);
        }
        if (!AccountUtil.checkPassword(password)) {
            throw new SdkException(ErrorConstants.INVALID_PASSWORD);
        }
        if (AccountUtil.checkMobile(account)) {//手机号注册
            Integer userId = userService.doRegistByNum(account, code, password);
            if (userId != null) {//注册失败
                return new ResponseTO(true, "");
            }
        }
        return new ResponseTO();
    }
}
